<template>
 <p>
    Ask a yes/no question:
    <input v-model="question" :disabled="loading" />
  </p>
  <p>{{ answer }}</p>

</template>

<script setup>
import { ref, watch,computed,reactive } from 'vue'
//   1. ref 是 Vue 3 中用于创建响应式数据的一种方式。如果 watch 观察的是一个 ref，当该 ref 的值发生变化时，会触发回调。
const count = ref(0);

watch(count, (newValue, oldValue) => {
  console.log(`count changed from ${oldValue} to ${newValue}`);
});


// 修改 count 的值
count.value = 1;  // 输出: count changed from 0 to 1


// 2.同样，如果你有一个计算属性，它也是一个“响应式的数据源”，watch 也能观察它的变化。
 count.value = 0;
const doubleCount = computed(() => count.value * 2);

watch(doubleCount, (newValue, oldValue) => {
  console.log(`doubleCount changed from ${oldValue} to ${newValue}`);
});

// 修改 count 的值
count.value = 2;  // 输出: doubleCount changed from 0 to 4

// 3.如果 watch 观察的是一个响应式对象，当对象的属性发生变化时，回调也会触发。
const state = reactive({
  count: 0,
  name: 'Vue'
});

watch(state, (newValue, oldValue) => {
  console.log('State changed:', newValue, oldValue);
});

// 修改 state 中的属性
state.count = 1;  // 输出: State changed: { count: 1, name: 'Vue' } { count: 0, name: 'Vue' }

// 4.watch 的第一个参数可以是一个 getter 函数，这种方式下，你可以动态地观察一些计算出来的值，而不仅仅是数据本身。

state.count=0;

const getState = () => {
  return {
    count: state.count,
    name: state.name
  };
};

watch(getState, (newValue, oldValue) => {
  console.log('State changed:', newValue, oldValue);
});

// 修改 state 中的属性
state.count = 1;  // 输出: State changed: { count: 1, name: 'Vue' } { count: 0, name: 'Vue' }

// watch 也可以接受一个数组作为第一个参数，这样它可以同时观察多个响应式数据源的变化。当任一数据源发生变化时，回调函数会被触发。
state.count = 0;

watch([() => state.count, () => state.name], ([newCount, newName], [oldCount, oldName]) => {
  console.log(`Count changed from ${oldCount} to ${newCount}`);
  console.log(`Name changed from ${oldName} to ${newName}`);
});

// 修改 state 中的属性
state.count = 1;  // 输出: Count changed from 0 to 1
state.name = 'React';  // 输出: Name changed from Vue to React
</script>

<style lang="scss" scoped>

</style>